package com.onion.utils.utils;

import com.google.common.collect.Lists;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 命令执行器
 * @author Archie
 */
public class CommandUtils {

    public static List<String> executeWithList(String command){
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            //执行Ping检查命令
            Process process = Runtime.getRuntime().exec(command);
            //获取响应结果
            inputStream = process.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            List<String> lineList = new ArrayList<>();
            String line;
            while((line=bufferedReader.readLine()) != null){
                lineList.add(line);
            }
            return lineList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try{
                if(bufferedReader != null){
                    bufferedReader.close();
                }
            }catch (IOException e1){}
            try{
                if(inputStreamReader != null){
                    inputStreamReader.close();
                }
            }catch (IOException e2){}
            try{
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (IOException e3){}
        }
    }

    public static String executeWithEncoding(String command, String encode){
        byte[] bytes = CommandUtils.execute(command);
        try {
            return new String(bytes, encode);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] execute(String command){
        InputStream inputStream = null;
        try {
            //执行命令
            Process process = Runtime.getRuntime().exec(command);
            //获取响应结果
            inputStream = process.getInputStream();
            int readByte = 0;
            List<Byte> listBytes = Lists.newArrayList();
            while((readByte=inputStream.read()) != -1){
                listBytes.add((byte)readByte);
            }
            byte[] bytes = new byte[listBytes.size()];
            for(int i=0; i<bytes.length; i++){
                bytes[i] = listBytes.get(i);
            }
            return bytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try{
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (IOException e){}
        }

    }

}